from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

from config import settings
from ioservice.common import initial_ioservice, close_ioservice


load_dotenv()
logger.add('runtime_{time}.log', rotation='1 week', encoding='utf-8')

app = FastAPI(title=settings.basic['project_name'])

# init data server connection
app.add_event_handler("startup", initial_ioservice)
app.add_event_handler("shutdown", close_ioservice)

# add middleware, after init logger & data server connection, in case middleware use them
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# app.mount("/static", StaticFiles(directory=settings.basic['static_basic_path']), name="static")

# config api router
from api.dataapi import dataapi
from api.funcapi import funcapi
from api import common

app.include_router(common.router)
app.include_router(dataapi.dataapi_router, prefix="/data")
app.include_router(funcapi.funcapi_router, prefix="/func")

if __name__ == '__main__':
    import uvicorn

    uvicorn.run("main:app", host="0.0.0.0", port=10001, reload=True)
